package com.wgchao.identityrightsmanagement.domain.organization.model;

import com.wgchao.identityrightsmanagement.domain.IdentifiedDomainObject;
import com.wgchao.identityrightsmanagement.infrastructure.exception.ObjectDisabledException;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * @ClassName: Agency
 * @author: wgchao
 * @createTime: 2020/6/6 7:54 AM
 * @Description: 机构
 */
@Getter
@Setter(AccessLevel.PROTECTED)
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class Agency extends IdentifiedDomainObject {

    //机构编号-唯一
    private String agencyCode;

    //机构名称
    private String agencyName;

    //地址
    private Address address;

    //描述
    private String description;

    //是否可用
    private boolean disabled;

    public Agency(Long id, String agencyCode, String agencyName, Address address, String description, boolean disabled, Long version) {
        this.setId(id);
        this.agencyCode = agencyCode;
        this.agencyName = agencyName;
        this.address = address;
        this.description = description;
        this.disabled = disabled;
        this.setVersion(version);
    }

    //创建新的机构
    public static Agency createAgency(String agencyCode, AgencyCreator agencyCreator){
        return new Agency(agencyCode, agencyCreator.getAgencyName(),
                new Address(agencyCreator.getProvince(), agencyCreator.getCity(), agencyCreator.getCounty(), agencyCreator.getXxaddress()),
                agencyCreator.getDescription(), false);
    }

    //修改机构基础信息
    public void modifyAgencyInfo(AgencyUpdator agencyUpdator){
        if(!normal()){
            throw new ObjectDisabledException("机构不可用");
        }
        if(agencyUpdator.getAgencyName() != null){
            this.agencyName = agencyUpdator.getAgencyName().get();
        }
        if(agencyUpdator.getDescription() != null){
            this.description = agencyUpdator.getDescription().orElse(null);
        }
        if(agencyUpdator.address()){
            this.address = new Address(agencyUpdator.getProvince()==null?this.address.getProvince():agencyUpdator.getProvince().orElse(null),
                    agencyUpdator.getCity()==null?this.address.getCity():agencyUpdator.getCity().orElse(null),
                    agencyUpdator.getCounty()==null?this.address.getCounty():agencyUpdator.getCounty().orElse(null),
                    agencyUpdator.getXxaddress()==null?this.address.getXxaddress():agencyUpdator.getXxaddress().orElse(null));
        }
    }

    //机构状态是否正常
    public boolean normal(){
        return !this.disabled;
    }

    public void normalException(){
        if(!this.normal()){
            throw new ObjectDisabledException(this.agencyName+"机构不可用");
        }
    }

    //禁用
    public void disable(){
        this.disabled = true;
    }
    //恢复使用
    public void regain(){
        this.disabled = false;
    }

}
